package util.thread.threadpool;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 创建一个指定工作线程数量的线程池，如果线程数量达到初始化大小，则将提交的任务保存到池队列中。提高效率节省开销，不会释放空闲资源。
 *
 * @author: Lidong
 * @time: 2020/8/6 20:42
 **/
public class FixThreadPoolTest {

    private static final Logger logger = LoggerFactory.getLogger(FixThreadPoolTest.class);

    public static void userFixThreadPool() throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            int index = i;
            executor.execute(() -> {
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
                logger.info("{}  {}", Thread.currentThread().getName(), index);
            });
        }
        executor.shutdown();
    }

    @Test
    public void test() {
        try {
            userFixThreadPool();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
